<?php
/**
 * +----------------------------------------------------------------------
 * | [ DO WHAT YOU LOVE AND FUCK THE REST ]
 * +----------------------------------------------------------------------
 * | EMAIL: < 931274989@qq.com >
 * +----------------------------------------------------------------------
 * | WECHAT: xzc016
 * +----------------------------------------------------------------------
 * | 管理员模型
 * +----------------------------------------------------------------------
 */
namespace app\admin\model;

use app\common\model\System;
use app\admin\service\Permissions;

use think\facade\Db;
use think\facade\Event;
use think\facade\Request;
use think\facade\Session;

class Admin extends Base
{
  /**
   * 隐藏非必要数据
   */
  protected $hidden = ['update_time'];

  /**
   * 一对一关联用户权限组关联模型
   */
  public function adminUid()
  {
    return $this->belongsTo('AuthGroupAccess','id','uid');
  }

  /**
   * 管理员登录校验
   * @return array|\think\response\Json
   * @throws \think\Exception
   */
  public static function checkLogin()
  {
    //查找格式化所有系统设置表数据
    $system = System::where('web','web')->find();
    $username = Request::param("username");
    $password = Request::param("password");
    $open_code = $system['code'];
    
    // 验证码验证
    if ($open_code) {
      $code = Request::param("vercode");
      if (!captcha_check($code)) {
        $data = ['error' => '1', 'msg' => '验证码错误'];
        return json($data);
      }
    }

    $result = self::where(['username' => $username, 'password' => password($password)])->find();
    if (empty($result)) $result = self::where(['tel' => $username, 'password' => password($password)])->find();
    if (empty($result)) {
      $data = ['error' => '1', 'msg' => '帐号或密码错误'];
      return json($data);
    } else {
      // token验证
      // $check = Request::checkToken('__token__');
      // if (false === $check) {
      //   $data = ['error' => '1', 'msg' => '验证有误'];
      //   return json($data);
      // }
      
      if ($result['status'] == 1) {
        $uid = $result['id'];

        // 权限组验证
        $group = AuthGroupAccess::with('adminGroup')
          ->where('uid', $uid)
          ->find();
        if (empty($group) || $group['adminGroup']['status'] != 1) {
          return json(['error' => 1, 'msg' => '权限组被删除或被禁用！']);
        }

        // 更新登录IP和登录时间
        self::where('id', '=', $result['id'])
          ->update(['login_time' => time(), 'login_ip' => Request::ip()]);
        
        // 查找规则
        $rules = self::rules_str($uid);

        // 登录成功写入session
        self::set_session($result,$rules);

        // 触发登录成功事件
        Event::trigger('AdminLogin', $result);

        $data = ['error' => '0', 'url' => url('Index/index')->__toString(), 'msg' => '登录成功'];
        return json($data);
      } else {
        return json(['error' => 1, 'msg' => '用户已被禁用!']);
      }

    }
  }

  /**
   * 登录成功写入session
   * @return array|\think\response\Json
   * @throws \think\Exception
   */
  private static function set_session($result,$rules)
  {
    Session::set('admin', [
      'id'        => $result['id'],
      'username'  => $result['username'],
      'nickname'  => $result['nickname'],
      'image'     => $result['image'],
    ]);

    Session::set('admin.group_id' , $rules['group_id']);
    Session::set('admin.rules'    , explode(',', $rules['rules']));
    Session::set('admin.title'    , $rules['title']);
  }
  
  /**
   * 查找规则
   * @return array|\think\response\Json
   * @throws \think\Exception
   */
  private static function rules_str($uid)
  {
    $rules = Db::name('auth_group_access')
    ->alias('a')
    ->leftJoin('auth_group ag', 'a.group_id = ag.id')
    ->field('a.group_id,ag.rules,ag.title')
    ->where('uid', $uid)
    ->find();
    $authOpensStr = Permissions::auth_opens();
    $rules['rules'] = $rules['rules'] . $authOpensStr;
    return $rules;
  }

}